/*
 * @Author: wuqingchun
 * @Date: 2024-07-23 14:55:25
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-07-26 16:52:21
 */
#include <vector>
#include <thread>

#include "object_pool.h"
#include "thread_cache.h"


void benchmark_test()
{
    const size_t ROUND = 5;
    const size_t TIMES_PER_ROUND = 1000000;
    std::vector<int*> vecData;
    vecData.reserve(TIMES_PER_ROUND);

    size_t ulBegin1 = clock();

    for (size_t ulRound = 0; ulRound < ROUND; ulRound++)
    {
        for (size_t ulTimes = 0; ulTimes < TIMES_PER_ROUND; ulTimes++)
        {
            vecData.push_back(new int());
        }

        for (size_t ulTimes = 0; ulTimes < TIMES_PER_ROUND; ulTimes++)
        {
            delete vecData[ulTimes];
        }

        vecData.clear();
    }

    size_t ulEnd1 = clock();


    std::vector<int*> vecData2;
    vecData2.reserve(TIMES_PER_ROUND);
    ObjectPool<int> objPool;
    size_t ulBegin2 = clock();
    
    for (size_t ulRound = 0; ulRound < ROUND; ulRound++)
    {
        for (size_t ulTimes = 0; ulTimes < TIMES_PER_ROUND; ulTimes++)
        {
            vecData2.push_back(objPool.New());
        }

        for (size_t ulTimes = 0; ulTimes < TIMES_PER_ROUND; ulTimes++)
        {
            objPool.Delete(vecData2[ulTimes]);
        }

        vecData2.clear();
    }

    size_t ulEnd2 = clock();

    std::cout << "Use new/delete: " << ulEnd1 - ulBegin1 << std::endl;
    std::cout << "Use ObjectPool: " << ulEnd2 - ulBegin2 << std::endl;
}


ThreadCache& GetThreadCache()
{
    static thread_local ThreadCache objTCache;

    return objTCache;
}


void* Alloc(size_t ulSize)
{
    return GetThreadCache().Alloc(ulSize);
}



void tcm_benchmark()
{
    std::thread objT1([](){
        for (int i = 0; i < 1 << 18; i++)
        {
            void* pMem = Alloc(i+1);
            if (pMem == nullptr)
            {
                printf("Error\n");
            }
        }
    });

    // std::thread objT2([](){
    //     for (int i = 0; i < 1 << 18; i++)
    //     {
    //         void* pMem = Alloc(i+1);
    //         if (pMem != nullptr)
    //         {
    //             printf("Error\n");
    //         }
    //     }
    // });

    objT1.join();
    // objT2.join();
}

int main(int argc, char** argv)
{
    //benchmark_test();
    tcm_benchmark();

    return 0;
}